<template>
  <el-dialog title="excel生成记录" :before-close="downExport" :visible.sync="exportExcelFlag" :close-on-click-modal="false"
    width="1200px" top="40px" class="add" @click="downExport">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane v-if="isExport" :label="tabTitle" name="export">
        <div>
          <div v-if="handleType == 'customer'" class="right-content scrollbar mb20">
            <el-card>
              <el-tree ref="tree" :data="menuList" :indent="0" show-checkbox node-key="field" default-expand-all
                :expand-on-click-node="false" :default-checked-keys="checkedList" @check="handleTwoChange">
                <div slot-scope="{ data }">
                  <span>{{ data.title }}</span>
                </div>
              </el-tree>
            </el-card>
          </div>
          <div class="export_right">
            <el-button type="primary" size="small" @click="confirmExport">确定导出</el-button>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="isExportFollow" label="跟进导出" name="follow_export">
        <el-form ref="form" :model="excelInfo" label-width="120px">
          <el-form-item :label="
              handleType == 'leads'
                ? '线索状态'
                : handleType == 'customer'
                  ? '客户状态'
                  : '经销商状态'
            ">
            <el-select v-model="condition" clearable multiple size="small" class="w300" placeholder="请选择"
              @change="selctChange">
              <el-option v-for="item in options.type" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="跟进时间">
            <el-date-picker v-model="followDateRange" size="small" type="daterange" range-separator="至"
              value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"
              @change="(val) => changeDateRange('follow', val)" />
          </el-form-item>
        </el-form>
        <div class="export_right">
          <el-button type="primary" size="small" @click="followEXport">确定导出</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="导出记录" name="export_record">
        <div v-show="recordFlag">
          <!--检索条件-->
          <el-form class="row" :inline="true" size="mini" :model="exportInfo">
            <div style="width: 100%">
              <el-form-item v-if="handleType != 'dealer'" label="数据类型">
                <el-select v-model="exportInfo.type_son" class="w130" clearable>
                  <el-option v-for="item in typeSon.type" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="生成时间">
                <el-date-picker v-model="dateRange" class="w250" type="daterange" range-separator="至"
                  value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期"
                  @change="(val) => changeDateRange('generate', val)" />
              </el-form-item>
              <el-form-item>
                <div class="flex">
                  <el-button type="primary" class="right" @click="getList('search', '搜索')">搜索</el-button>
                </div>
              </el-form-item>
            </div>
          </el-form>
          <!--列表-->
          <el-table :data="list" size="small" :cell-style="$style.cellStyle" :header-cell-style="$style.rowClass">
            <ElTableColumn label="文件名称" prop="file_name" />
            <ElTableColumn label="生成时间" prop="create_time" />
            <ElTableColumn v-if="handleType == 'dealer'" label="生成人" prop="user_name" />
            <ElTableColumn v-else label="生成人" prop="realname" />
            <ElTableColumn label="操作" width="200">
              <template slot-scope="{ row }">
                <div class="flex_center">
                  <el-button type="text" size="mini" @click="openDialog(row)">下载</el-button>
                  <el-button type="text" size="mini" @click="downRecord('down', row)">下载记录</el-button>
                </div>
              </template>
            </ElTableColumn>
          </el-table>
          <!--分页-->
          <pagination class="page tc mt10" :total="page.total" :page.sync="page.page" :limit.sync="page.limit"
            @pagination="getList" />
        </div>
        <div v-show="!recordFlag">
          <div class="row mb15">
            <div class="left row">
              <div>
                <div class="fwb mb5 fz16">{{ detail.file_name }}</div>
                <div v-if="handleType == 'dealer'" class="fz12 mt10">
                  由【{{ detail.user_name }}】于【{{ detail.create_time }}】生成
                </div>
                <div v-else class="fz12 mt10">
                  由【{{ detail.realname }}】于【{{ detail.create_time }}】生成
                </div>
              </div>
            </div>
            <div class="right flex">
              <el-button size="small" class="mr20" type="primary" @click="downRecord">返回</el-button>
            </div>
          </div>
          <div class="row">
            <el-table :data="recordList" size="small" :cell-style="$style.cellStyle"
              :header-cell-style="$style.rowClass">
              <ElTableColumn label="导出时间" prop="create_time" />
              <ElTableColumn v-if="handleType == 'dealer'" label="导出人" prop="user_name" />
              <ElTableColumn v-else label="导出人" prop="realname" />
            </el-table>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
class ExcelInfo {
  trans_status = []; // 线索状态
  customer_status = [];
  sdate = ''; // 线索跟进日期【开始】
  edate = ''; //	线索跟进日期【结束】 日期跨度不超30天
  start_time = '';
  end_time = '';
}
class ExportInfo {
  type_son = ''; // 0 = 全部 1 = 线索数据 2 = 跟进数据
  sdate = '';
  edate = '';
  start_time = '';
  end_time = '';
}
class Options {
  constructor(type) {
    switch (type) {
      case 'customer':
        this.type = [
          {
            id: 1,
            name: '待处理'
          },
          {
            id: 2,
            name: '已成交'
          },
          {
            id: 3,
            name: '未成交'
          }
        ];
        break;
      case 'leads':
        this.type = [
          {
            id: 0,
            name: '待处理'
          },
          {
            id: 1,
            name: '已成交'
          },
          {
            id: 3,
            name: '未成交'
          }
        ];
        break;
      case 'dealer':
        this.type = [
          { id: 1, name: '待触达' },
          { id: 2, name: '待认证' },
          { id: 3, name: '认证中' },
          { id: 4, name: '已驳回' },
          { id: 5, name: '已认证' },
          { id: 6, name: '已成交' },
          { id: 7, name: '已作废' },
          { id: 8, name: '已关闭' }
        ];
        break;
    }
  }
}
class TypeSon {
  constructor(type) {
    switch (type) {
      case 'customer':
        this.type = [];
        break;
      case 'leads':
        this.type = [];
        break;
    }
  }
}
class Page {
  total = 0;
  page = 1;
  limit = 10;
}
import {
  leadsExport,
  followRecordExport,
  excelExportLog,
  excelDown,
  excelDownLog,
  exportFieldList,
  exportinfo,
  exportInfoList,
  exportCustomer,
  downExcelLog,
  downExcel,
  exportFollowRecord,
  exportFollowRecordList,
  downloadFollowRecord,
  exportFollowRecordDownload
} from '@/api/export';
import pagination from '@/components/Pagination';
export default {
  name: 'ExportExcel',
  components: {
    pagination
  },
  props: {
    exportExcelFlag: {
      type: Boolean,
      default: false
    },
    tabTitle: {
      type: String,
      default: ''
    },
    handleType: {
      type: String,
      default: 'client'
    },
    isExport: {
      type: Boolean,
      default: true
    },
    isExportFollow: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      activeName: 'export',
      options: new Options(this.handleType),
      excelInfo: new ExcelInfo(), // 跟进导出
      exportInfo: new ExportInfo(), // 导出记录
      typeSon: new TypeSon(this.handleType),
      page: new Page(), // 分页
      detail: {},
      followDateRange: [],
      condition: [], // 状态
      dateRange: [],
      list: [], // 导出记录列表
      recordList: [], // 导出记录详情列表
      menuList: [], // 客户树状图
      menusInfo: {
        customer: ['customer_id', '']
      }, // 当前所选项
      checkedList: [], // 默认选中项
      recordFlag: true // 下载记录
    };
  },
  watch: {
    exportExcelFlag (val) {
      if (this.handleType == 'dealer') {
        this.activeName = 'follow_export';
        this.condition = [1, 2, 3, 4, 5, 6];
        this.excelInfo.trans_status = [1, 2, 3, 4, 5, 6];
      } else if (this.handleType == 'customer') {
        this.condition = [1, 2, 3];
        this.excelInfo.customer_status = [1, 2, 3];
      } else if (this.handleType == 'leads') {
        this.condition = [0, 1, 3];
        this.excelInfo.trans_status = [0, 1, 3];
      }
    }
  },
  methods: {
    // 打开抽屉初始化
    openDrawer () {
      if (this.isExport && !this.isExportFollow) {
        this.typeSon.type = [
          { id: 1, name: this.handleType == 'leads' ? '线索数据' : '客户数据' }
        ];
        this.exportInfo.type_son = 1;
      } else if (!this.isExport && this.isExportFollow) {
        this.typeSon.type = [{ id: 2, name: '跟进数据' }];
        this.exportInfo.type_son = 2;
      } else if (this.isExport && this.isExportFollow) {
        this.typeSon.type = [
          {
            id: 0,
            name: '全部'
          },
          {
            id: 1,
            name: '客户数据'
          },
          {
            id: 2,
            name: '跟进数据'
          }
        ];
        this.exportInfo.type_son = 0;
      }
      if (this.handleType == 'customer') {
        this.exportList();
      }
    },
    // 搜索
    getList (option) {
      switch (this.handleType) {
        case 'leads':
          this.leadsExportRecord(option);
          break;
        case 'customer':
          this.customerExportRecord(option);
          break;
        case 'dealer':
          this.dealerExportRecord(option);
          break;
      }
    },
    // 跟进状态选择
    selctChange (val) {
      console.log(val);
      if (this.handleType == 'customer') {
        this.excelInfo.customer_status = val;
      } else {
        this.excelInfo.trans_status = val;
      }
    },
    // 头部切换
    handleClick (tab) {
      if (this.handleType == 'leads') {
        if (tab.name == 'export_record') {
          this.recordFlag = true;
          this.leadsExportRecord();
        }
      } else if (this.handleType == 'customer') {
        if (tab.name == 'export_record') {
          this.recordFlag = true;
          this.customerExportRecord();
        }
      } else {
        if (tab.name == 'export_record') {
          this.recordFlag = true;
          this.dealerExportRecord();
        }
      }
    },
    // 获取客户导出记录
    async customerExportRecord (option) {
      if (option === 'search') this.page = new Page();
      try {
        const { list, dataCount } = await exportInfoList({
          ...this.page,
          ...this.exportInfo
        });
        this.list = list;
        this.page.total = dataCount;
      } catch (e) {
        this.list = [];
        this.page.total = 0;
      }
    },
    // 获取树状图
    async exportList () {
      const data = await exportFieldList();
      data.forEach((item) => {
        item.children.forEach((val) => {
          val.field = item.field + '*' + val.field;
        });
        item.children[0].disabled = true;
        item.children[1].disabled = true;
        this.checkedList.push(item.children[0].field, item.children[1].field);
      });
      this.menuList = data;
      this.$nextTick(() => {
        // 树状图最底层添加样式 display: inline-block
        this.$refs.tree.$el
          .querySelectorAll('.el-tree-node__children:empty')
          .forEach((node) => {
            node.parentNode.style.display = 'inline-block';
          });
      });
      let customer = this.checkedList
        .filter((val) => {
          return val.indexOf('customer*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      let contact = this.checkedList
        .filter((val) => {
          return val.indexOf('contact*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      let address = this.checkedList
        .filter((val) => {
          return val.indexOf('address*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      let competitor = this.checkedList
        .filter((val) => {
          return val.indexOf('competitor*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      let change_good = this.checkedList
        .filter((val) => {
          return val.indexOf('change_good*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      this.menusInfo = { customer, contact, address, competitor, change_good };
    },
    // 线索导出记录
    async leadsExportRecord (option) {
      if (option === 'search') this.page = new Page();
      try {
        const { list, dataCount } = await excelExportLog({
          ...this.page,
          ...this.exportInfo
        });
        this.list = list;
        this.page.total = dataCount;
      } catch (e) {
        this.list = [];
        this.page.total = 0;
      }
    },
    // 经销商导出记录
    async dealerExportRecord (option) {
      if (option === 'search') this.page = new Page();
      this.exportInfo.type_son = 2;
      try {
        const { list, dataCount } = await exportFollowRecordList({
          ...this.page,
          ...this.exportInfo
        });
        this.list = list;
        this.page.total = dataCount;
      } catch (e) {
        this.list = [];
        this.page.total = 0;
      }
    },
    // 日期判断
    // calculateDate(val) {
    //   let start_time = val[0].replace(/-/g, '');
    //   let end_time = val[1].replace(/-/g, '');
    //   if (end_time - start_time > 100) {
    //     this.$message('选择时间不能大于30天');
    //   }
    // },
    // 日期选择
    changeDateRange (option, val) {
      if (option == 'follow') {
        // this.calculateDate(val);
        if (this.handleType == 'leads') {
          this.excelInfo.sdate = this.followDateRange
            ? this.followDateRange[0]
            : '';
          this.excelInfo.edate = this.followDateRange
            ? this.followDateRange[1]
            : '';
        } else {
          this.excelInfo.start_time = this.followDateRange
            ? this.followDateRange[0]
            : '';
          this.excelInfo.end_time = this.followDateRange
            ? this.followDateRange[1]
            : '';
        }
      } else {
        if (this.handleType == 'leads') {
          this.exportInfo.sdate = this.dateRange ? this.dateRange[0] : '';
          this.exportInfo.edate = this.dateRange ? this.dateRange[1] : '';
        } else {
          this.exportInfo.start_time = this.dateRange ? this.dateRange[0] : '';
          this.exportInfo.end_time = this.dateRange ? this.dateRange[1] : '';
        }
      }
    },
    // 关闭导出弹框
    downExport () {
      this.excelInfo = new ExcelInfo();
      this.exportInfo = new ExportInfo();
      this.followDateRange = [];
      this.dateRange = [];
      this.$emit('close', 'export');
    },
    // 导出确认
    confirmExport () {
      switch (this.handleType) {
        case 'leads':
          this.getLeads();
          break;
        case 'customer':
          this.getCustomer();
          break;
      }
    },
    // 跟进导出
    followEXport () {
      switch (this.handleType) {
        case 'leads':
          this.getFollowRecordExport();
          break;
        case 'customer':
          this.getCustomerFollow();
          break;
        case 'dealer':
          this.getDealerExport();
          break;
      }
    },
    // 客户导出
    async getCustomer () {
      this.$notify({
        title: '成功',
        message: '数据生成中，请前往导出记录中进行导出！',
        type: 'success'
      });
      const { msg } = await exportinfo(this.menusInfo);
    },
    // 线索导出
    async getLeads () {
      this.$notify({
        title: '成功',
        message: '数据生成中，请前往导出记录中进行导出！',
        type: 'success'
      });
      const data = await leadsExport();
    },
    // 经销商跟进导出
    async getDealerExport () {
      let excelInfo = {
        start_time: this.excelInfo.start_time,
        end_time: this.excelInfo.end_time,
        status: this.excelInfo.trans_status
      };
      let start_time = this.excelInfo.start_time.replace(/-/g, '');
      let end_time = this.excelInfo.end_time.replace(/-/g, '');
      if (end_time - start_time > 100) {
        return this.$message('选择时间不能大于30天');
      }
      const res = await exportFollowRecord({ ...excelInfo });
      this.$message({
        message: `导出成功`,
        type: 'success'
      });
      this.followDateRange = [];
    },
    // 客户跟进导出
    async getCustomerFollow () {
      let start_time = this.excelInfo.start_time.replace(/-/g, '');
      let end_time = this.excelInfo.end_time.replace(/-/g, '');
      if (end_time - start_time > 100) {
        return this.$message('选择时间不能大于30天');
      }
      const data = await exportCustomer({ ...this.excelInfo });
      this.$message({
        message: `数据生成中，请前往导出记录中进行导出~`,
        type: 'success'
      });
      this.excelInfo = new ExcelInfo();
    },
    // 线索跟进导出
    async getFollowRecordExport () {
      let start_time = this.excelInfo.sdate.replace(/-/g, '');
      let end_time = this.excelInfo.edate.replace(/-/g, '');
      if (end_time - start_time > 100) {
        return this.$message('选择时间不能大于30天');
      }
      const data = await followRecordExport({ ...this.excelInfo });
      this.$message({
        message: `成功导出${data.count}条有效数据`,
        type: 'success'
      });
      this.excelInfo = new ExcelInfo();
    },
    // 点击节点
    handleTwoChange (data, checked) {
      let selected = checked.checkedKeys;
      let customer = selected
        .filter((val) => {
          return val.indexOf('customer*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      let contact = selected
        .filter((val) => {
          return val.indexOf('contact*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      let address = selected
        .filter((val) => {
          return val.indexOf('address*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      let competitor = selected
        .filter((val) => {
          return val.indexOf('competitor*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      let change_good = selected
        .filter((val) => {
          return val.indexOf('change_good*') > -1;
        })
        .map((item) => {
          return item.split('*')[1];
        });
      this.menusInfo = { customer, contact, address, competitor, change_good };
    },
    // 下载记录
    downRecord (option, row) {
      if (option == 'down') {
        if (this.handleType == 'leads') {
          this.leadsDownloadDetail(row);
        } else if (this.handleType == 'customer') {
          this.customerDownloadDetail(row);
        } else {
          this.dealerDownloadDetail(row);
        }
      }
      this.recordFlag = !this.recordFlag;
    },
    // 线索下载记录接口
    async leadsDownloadDetail (row) {
      const data = await excelDownLog({ export_id: row.export_id });
      this.recordList = data;
      this.detail = {
        ...row
      };
    },
    // 客户下载记录接口
    async customerDownloadDetail (row) {
      const data = await downExcelLog({ export_id: row.export_id });
      this.recordList = data.list;
      this.detail = {
        ...row
      };
    },
    // 经销商下载记录接口
    async dealerDownloadDetail (row) {
      const data = await exportFollowRecordDownload({
        export_id: row.export_id
      });
      this.recordList = data;
      this.detail = {
        ...row
      };
    },
    // 下载
    openDialog (row) {
      switch (this.handleType) {
        case 'leads':
          this.leads_down(row);
          break;
        case 'customer':
          this.customer_down(row);
          break;
        case 'dealer':
          this.dealer_down(row);
          break;
      }
      // export_id
    },
    // 客户记录下载
    async customer_down (row) {
      const data = await downExcel({ export_id: row.export_id });
      const loading = this.$loading({
        lock: true,
        text: '文件导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let a = document.createElement('a');
      a.setAttribute('href', data.url);
      a.setAttribute('download', data.url);
      if (navigator.msSaveBlob) {
        //     // 兼容IE
        var blob = Blob([blob], { type: 'xlsx' });
        return navigator.msSaveBlob(blob, '客户列表.xlsx');
      }
      a.click();
      setTimeout(() => {
        loading.close();
      }, 3000);
    },
    // 线索记录下载
    async leads_down (row) {
      const data = await excelDown({ export_id: row.export_id });
      const loading = this.$loading({
        lock: true,
        text: '文件导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let a = document.createElement('a');
      a.setAttribute('href', data.path);
      a.setAttribute('download', data.path);
      if (navigator.msSaveBlob) {
        //     // 兼容IE
        var blob = Blob([blob], { type: 'xlsx' });
        return navigator.msSaveBlob(blob, '线索列表.xlsx');
      }
      a.click();
      setTimeout(() => {
        loading.close();
      }, 3000);
    },
    // 经销商记录下载11
    async dealer_down (row) {
      const data = await downloadFollowRecord({ export_id: row.export_id });
      const loading = this.$loading({
        lock: true,
        text: '文件导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let a = document.createElement('a');
      a.setAttribute('href', data.download_url);
      a.setAttribute('download', data.download_url);
      if (navigator.msSaveBlob) {
        //     // 兼容IE
        var blob = Blob([blob], { type: 'xlsx' });
        return navigator.msSaveBlob(blob, '线索列表.xlsx');
      }
      a.click();
      setTimeout(() => {
        loading.close();
      }, 3000);
    }
  }
};
</script>

<style lang="scss" scoped>
.right-content {
  overflow: auto;
  height: calc(100vh - 300px);
  .el-tree {
    ::v-deep.el-tree-node {
      white-space: inherit;
      margin-bottom: 5px;
      .el-tree-node__content {
        margin-bottom: 15px;
        width: 200px;
        .el-tree-node__expand-icon {
          display: none;
        }
      }
    }
  }
}
.export_right {
  display: flex;
  justify-content: end;
}
.add {
  background: #f5f6f9;
  ::v-deep.el-dialog {
    height: calc(100vh - 80px);
    overflow-y: auto;
  }
  ::v-deep.el-dialog__body {
    padding: 10px 20px;
  }
  ::v-deep.el-radio {
    margin-bottom: 15px;
  }
}
</style>
